package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.heima.mapper.ApArticleConfigMapper;
import com.heima.mapper.ApArticleContentMapper;
import com.heima.mapper.ApArticleMapper;
import com.heima.mapper.AuthorMapper;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.search.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    ApArticleContentService apArticleContentService;
    @Autowired
    ApArticleConfigService apArticleConfigService;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    AuthorService authorService;
    @Autowired
    GeneratePageService generatePageService;

    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public void publishArticle(Integer newsId) {
        //  1  获取wmUser对象
        WmNews wmNews = getWmNews(newsId);

        //  封装到ap_article
        ApArticle apArticle = getApArticle(wmNews);

        // 保存保存或修改 article信息
        saveOrUpdateArticle(apArticle);

        //  封装 articleConfig
        ApArticleConfig apArticleConfig =getArticleConfig(apArticle.getId());
        //  封装 articleContent
        ApArticleContent apArticleContent =getArticleContent(wmNews,apArticle.getId());
        //  保存  config和content 关系
        saveConfigAndContent(wmNews, apArticle);
        //  页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
        //  更新news 状态
        updateWmNews(newsId, wmNews, apArticle);

    }

    /**
     *      封装  ApArticle
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        // 拷贝属性

        BeanUtils.copyProperties(wmNews,apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte)0); // 普通文章
        apArticle.setLayout(wmNews.getType());// 布局

        //  获取作者姓名
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if(author == null){
            log.error("文章发布失败 未查询到相关作者信息， 不予发布 , 文章id : {}  自媒体用户id : {}",wmNews.getId(),wmNews.getUserId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"根据自媒体用户，查询关联作者信息失败");
        }
        apArticle.setAuthorId(Long.valueOf(author.getId()));

        apArticle.setAuthorName(author.getName());
        //  获取频道名
        String channelName = findChannelName(wmNews.getChannelId());
        apArticle.setChannelName(channelName);
        return apArticle;
    }

    /**
     *      获取WmNews
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        ResponseResult<WmNews> wemediaFeignResult = wemediaFeign.findWmNewsById(newsId);
        //  监测feign  调用是否成功
        if (!wemediaFeignResult.checkCode()) {
            log.error("wemediaFeign远程调用失败{}",newsId);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"wemediaFeign远程调用失败");
        }
        WmNews wmNews = wemediaFeignResult.getData();
        if(wmNews == null){
            log.error("文章发布失败 未获取到自媒体文章信息  文章id: {}",newsId);
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到自媒体文章");
        }
        if (!(wmNews.getStatus() == 4 || wmNews.getStatus() == 8)) {
            log.info("文章审核不通过，不能进行后续发布{}",newsId);
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        return wmNews;
    }

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    private String webSite;
    /**
     * 根据参数加载文章列表
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        //2 执行查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle apArticle : articleList) {
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
            System.err.println(apArticle.getStaticUrl());
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(articleList);
        result.setHost(webSite);
        return result;

    }

    @Override
    public ResponseResult load2(Short loadtype , ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage) {
            // redis
            String articleListJson = (String) redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleListJson)) {
                List<ApArticle> apArticles = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
                }
                ResponseResult result = ResponseResult.okResult(apArticles);
                result.setHost(webSite);

                return result;
            }
        }

        return load(loadtype, dto);

    }

    /**
     *      保存或者修改文章
     * @param apArticle
     */
    private void saveOrUpdateArticle(ApArticle apArticle){
        // 判断wmNews之前是否关联 articleId
        if(apArticle.getId() == null){
            // 无关联  新增 article
            // 保存文章

            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            save(apArticle);

        }else {
            // 有关联  修改 article
            // 修改文章  删除之前关联的配置信息   内容信息
            ApArticle article = getById(apArticle.getId());
            if(article == null){
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的文章不存在");
            }
            updateById(apArticle);
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
        }
    }

    /**
     *      更新news状态
     * @param newsId
     * @param wmNews
     * @param apArticle
     */
    private void updateWmNews(Integer newsId, WmNews wmNews, ApArticle apArticle) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(apArticle.getId());
        ResponseResult feignResult = wemediaFeign.updateWmNews(wmNews);
        if (!feignResult.checkCode()) {
            log.error("wemediaFeign远程调用失败{}",newsId);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"wemediaFeign远程调用失败");

        }

    }


    /**
     *      保存 文章关系
     * @param
     */
    private void saveConfigAndContent(WmNews wmNews,ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        //添加文件详情
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());

        apArticleContentMapper.insert(apArticleContent);
    }


    /**
     *      封装ArticleContent
     * @param id
     * @return
     */
    private ApArticleContent getArticleContent(WmNews wmNews,Long id) {

        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(id);
        //  获取content并注入
        apArticleContent.setContent(wmNews.getContent());
        return apArticleContent;
    }

    /**
     *      封装ArticleConfig
     * @param id
     * @return
     */
    private ApArticleConfig getArticleConfig(Long id) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(id);
        return apArticleConfig;
    }



    /**
     *      获取channelName
     * @param channelId
     * @return
     */
    private String findChannelName(Integer channelId) {
        ResponseResult<AdChannel> feignResult = adminFeign.findOne(channelId);
        if (!(feignResult.checkCode())) {
            log.error("adminFeign远程调用失败{}",channelId);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"adminFeign远程调用失败");
        }
        AdChannel channel = feignResult.getData();
        return channel.getName();
    }

    /**
     *      根据用户id   查询用户名字
     * @param wmUserId
     * @return
     */
    private String findAuthorName(Integer wmUserId) {
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmUserId));
        //pAuthor apAuthor = authorService.getById(wmUserId);
        return apAuthor.getName();
    }
}